package com.wlbx.agent.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Base64;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wlbx.agent.R;
import com.wlbx.agent.base.BaseWebActivity;
import com.wlbx.agent.bean.AgentBean;
import com.wlbx.agent.bean.ProductListBean;
import com.wlbx.agent.global.Constant;
import com.wlbx.agent.util.BitMapUtil;
import com.wlbx.agent.util.Constants;
import com.wlbx.agent.util.FileUtil;
import com.wlbx.agent.util.FileUtils;
import com.wlbx.agent.util.LocationUtil;
import com.wlbx.agent.util.SPUtil;
import com.wlbx.agent.view.ShareDialog;
import com.wlbx.agent.view.ShareUtil;
import com.wlbx.agent.view.WeChatPresenter;
import com.wlbx.agent.view.bridge.BridgeHandler;
import com.wlbx.agent.view.bridge.BridgeWebView;
import com.wlbx.agent.view.bridge.BridgeWebViewClient;
import com.wlbx.agent.view.bridge.CallBackFunction;
import com.wlbx.agent.view.bridge.DefaultHandler;
import com.fastlib.utils.N;
import com.fastlib.utils.permission.FastPermission;
import com.fastlib.utils.permission.OnPermissionCallback;
import com.fastlib.utils.permission.Permission;
import com.ypx.imagepicker.ImagePicker;
import com.ypx.imagepicker.bean.ImageItem;
import com.ypx.imagepicker.bean.MimeType;
import com.ypx.imagepicker.bean.PickerError;
import com.ypx.imagepicker.data.OnImagePickCompleteListener;
import com.ypx.imagepicker.data.OnImagePickCompleteListener2;
import org.jetbrains.annotations.Nullable;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
//import io.microshow.rxffmpeg.RxFFmpegCommandList;
//import io.microshow.rxffmpeg.RxFFmpegInvoke;
//import io.microshow.rxffmpeg.RxFFmpegSubscriber;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class WebActivity extends BaseWebActivity {
    private static final String TAG = "WebActivity";

    @BindView(R.id.webView)
    BridgeWebView wvContent;
    @BindView(R.id.rl_title)
    RelativeLayout  rl_title;
    @BindView(R.id.tv_layout_top_back_title)
    TextView mTitleTV;
    @BindView(R.id.iv_layout_top_back)
    ImageView mBackIV;
    @BindView(R.id.iv_delete)
    ImageView mDelete;
    @BindView(R.id.iv_share)
    ImageView mShare;

    private String purl,url;
    private WebSettings webSettings;
    private IWXAPI wxApi;
    private static final int THUMB_SIZE = 150;
    protected Gson gson = new Gson();

    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> mUploadCallbackAboveL;
    private boolean isVideo = false;
    private String acceptType;
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int VIDEO_REQUEST = 110;
    private static final int FILECHOOSER_RESULTCODE = 2;
    private Uri imageUri;
    protected String mPlanShareUrl;
    protected LinkedList<String> urls;
    protected int cacheMode;
    protected long cacheTime;
    protected int openType;
    public final static String CACHE_MODE = "cache_mode";
    public final static int CACHE_NO = 0;//没有缓存
    public final static int CACHE_YES = 1;//有缓存
    public final static String CACHE_TIME = "cache_time";
    public static final String OPEN_TYPE = "open_type";
    public static final int OPEN_NEW = 12;
    public static final int OPEN_CURRENT = 13;
    public ProductListBean.DataDTO.ListDTO product;
    public PopupWindow mPopupShareWindow;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_web;
    }

    @SuppressLint("JavascriptInterface")
    @Override
    public void initData() {
        urls = new LinkedList<>();
        if(getIntent() != null) {
            product = (ProductListBean.DataDTO.ListDTO) getIntent().getSerializableExtra("bean");
            if (product != null && ("Y".equals(product.getIsOnline()) || product.getProductId()==1545)) {
                rl_title.setVisibility(View.VISIBLE);
                mTitleTV.setText(product.getProductName());
                if(product.getProductId()==1545) mShare.setVisibility(View.GONE);
            }else
                rl_title.setVisibility(View.GONE);
        }
        AgentBean ab = (AgentBean)SPUtil.getBean(Constant.USER_INFO,"agent");
        Logger.i("initData---ab---"+JSON.toJSONString(ab));
        addWXPlatform();
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectNetwork().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());
        if(product != null){
            purl = product.getProductUrl();
        }else{
            purl = getIntent().getExtras().getString("purl");
        }
        url = purl;
        wvContent = (BridgeWebView)findViewById(R.id.webView);
        webSettings = wvContent.getSettings();
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setDomStorageEnabled(true);// 打开本地缓存提供JS调用,至关重要
        webSettings.setAppCacheMaxSize(1024*1024*8);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        webSettings.setAppCachePath(appCachePath);
        webSettings.setAllowFileAccess(true);
//        webSettings.setDatabaseEnabled(true);
        //上面这些settings是实现localStorage需要的存储条件

        StringBuilder userAgentBuilder= new StringBuilder(webSettings.getUserAgentString());
        webSettings.setUserAgentString(userAgentBuilder.append(";").append("native_Andriod").append(";").append("ICBC-AXA-EJBB").toString());
        Logger.i("UserAgent----"+webSettings.getUserAgentString());

        wvContent.addJavascriptInterface(new JsObject(),"android");
        webSettings.setBlockNetworkImage(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webSettings.setMediaPlaybackRequiresUserGesture(false);
        }
        wvContent.setWebViewClient(new MyWebViewClient());
        wvContent.setWebChromeClient(new MyWebChromeClient());
        wvContent.setDefaultHandler(new DefaultHandler());
        wvContent.loadUrl(url);
        registerHandler(wvContent);
        add_ICBC_AXA_javascriptInterface(wvContent,gson);
    }

    @Override
    public void initEvent() {}

    @OnClick({R.id.iv_layout_top_back,R.id.iv_delete,R.id.iv_share})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_layout_top_back:
                if(wvContent.getUrl().equals(url) ){
                    this.finish();
                }else{
                    wvContent.goBack();
                }
                break;
            case R.id.iv_delete:
                finish();
                break;
            case R.id.iv_share:
                showPopupValidCodeWindow();
                break;
            default:
                break;
        }
    }

    public class JsObject{

    }
    //与H5交互操作
    public String getAgentData(String data) {
        AgentBean ab = (AgentBean)SPUtil.getBean(Constant.USER_INFO,"agent");
        Logger.i("ab---"+JSON.toJSONString(ab));
        JSONObject json = new JSONObject();
        if(ab!=null){
            json.put("accessToken",ab.getAccessToken());
            json.put("publicKey",ab.getPublicKey());
            json.put("image",ab.getImage());
            json.put("loginPwdFlag",ab.getLoginPwdFlag());
            json.put("name",ab.getName());
            json.put("workNo",ab.getWorkNo());
            json.put("iphone",ab.getMobile());
        }else{
            json.put("accessToken","");
            json.put("publicKey","");
        }
        return json.toJSONString();
    }

    public String showTitle(String data) {
        if(data != null) {
            JSONObject json = JSON.parseObject(data);
            rl_title.setVisibility(View.VISIBLE);
            mTitleTV.setText(json.getString("title"));
        }
        return "";
    }

    public String browserEnvironment(String data) {
        JSONObject json = new JSONObject();
            json.put("browser","android");
        return json.toJSONString();
    }

    public String openCamera(String data){
        FastPermission.with(WebActivity.this)
        .permissions(Permission.CAMERA,Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE)
        .request(new OnPermissionCallback() {
            @Override
            public void onPermissionSuccess() {
                ImagePicker.takePhoto(WebActivity.this, null, true, new OnImagePickCompleteListener() {
                    @Override
                    public void onImagePickComplete(ArrayList<ImageItem> items) {
                        uploadSingleCompressImage(items.get(0));
                    }
                });
            }
            @Override
            public void onPermissionFailure(String hint) {
                N.showShort(WebActivity.this,hint);
            }
        });
        return "";
    }

    public String weixinShare(String data) {
        if (!wxApi.isWXAppInstalled()) {
            Toast.makeText(mActivity,"您还没有安装微信",Toast.LENGTH_SHORT).show();
            return "";
        }
        JSONObject json =  JSON.parseObject(data);
        //0-分享微信 1-分享朋友圈
        String shareType = json.getString("shareType");
        // SendMessageToWX.Req.WXSceneSession是分享到好友会话
        // SendMessageToWX.Req.WXSceneTimeline是分享到朋友圈
        String titleName = json.getString("titleName");
        String content = json.getString("describe");
        String shareUrl =json.getString("shareUrl");
        String imageUrl = json.getString("imageUrl");
        if("0".equals(shareType)){
            // 初始化一个WXWebpageObject对象
            WXWebpageObject webpageObject = new WXWebpageObject();
            // 填写网页的url
            webpageObject.webpageUrl = shareUrl;
            // 用WXWebpageObject对象初始化一个WXMediaMessage对象
            WXMediaMessage msg = new WXMediaMessage(webpageObject);
            // 填写网页标题、描述、位图
            msg.title = titleName;
            msg.description = content;
            if (!TextUtils.isEmpty(imageUrl)){
                // 如果没有位图，可以传null，会显示默认的图片
                Bitmap bmp = BitMapUtil.getInstance().returnBitMap(imageUrl);
                Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
                bmp.recycle();
                msg.thumbData = bmpToByteArray(thumbBmp, true);
            }
            // 构造一个Req
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            // transaction用于唯一标识一个请求（可自定义）
            req.transaction = "webpage";
            // 上文的WXMediaMessage对象
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneSession;
            // 向微信发送请求
            wxApi.sendReq(req);
        }else if("1".equals(shareType)){
            // 初始化一个WXWebpageObject对象
            WXWebpageObject webpageObject = new WXWebpageObject();
            // 填写网页的url
            webpageObject.webpageUrl = shareUrl;
            // 用WXWebpageObject对象初始化一个WXMediaMessage对象
            WXMediaMessage msg = new WXMediaMessage(webpageObject);
            // 填写网页标题、描述、位图
            msg.title = titleName;
            msg.description = content;
            if (!TextUtils.isEmpty(imageUrl)){
                // 如果没有位图，可以传null，会显示默认的图片
                Bitmap bmp = BitMapUtil.getInstance().returnBitMap(imageUrl);
                Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
                bmp.recycle();
                msg.thumbData = bmpToByteArray(thumbBmp, true);
            }
            // 构造一个Req
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = "webpage";
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
            wxApi.sendReq(req);
        }
        return "";
    }

    public String weixinShareImage(String data) {
        if (!wxApi.isWXAppInstalled()) {
            Toast.makeText(mActivity,"您还没有安装微信",Toast.LENGTH_SHORT).show();
            return "";
        }
        JSONObject json =  JSON.parseObject(data);
        //0-分享微信 1-分享朋友圈
        String shareType = json.getString("shareType");
        String imageUrl = json.getString("imageUrl");
        Bitmap bitmap = BitMapUtil.getInstance().returnBitMap(imageUrl);
        WXImageObject imgObj = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        Bitmap thumbBitmap = Bitmap.createScaledBitmap(bitmap, THUMB_SIZE, THUMB_SIZE, true);
        bitmap.recycle();
        msg.thumbData = bmpToByteArray(thumbBitmap);  //设置缩略图
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("imgshareappdata");
        req.message = msg;
        req.scene = Integer.valueOf(shareType);
        wxApi.sendReq(req);
        return "";
    }

    public byte[] bmpToByteArray(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }


    public String appointViewController(String data) {
        JSONObject json =  JSON.parseObject(data);
        String pageIndex = json.getString("pageIndex");
        finish();
        Intent intent = new Intent(this,MainActivity.class);
        intent.putExtra("to",pageIndex);
        startActivity(intent);
        return "";
    }

    public String backLastPage(String data){
        finish();
        return "";
    }

    /**
     * @功能描述 : 添加微信平台分享
     * @return
     */
    private void addWXPlatform() {
        wxApi = WXAPIFactory.createWXAPI(this, Constants.WX_APPID);
        wxApi.registerApp(Constants.WX_APPID);
    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//        super.onActivityResult(requestCode, resultCode, intent);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            if (requestCode == REQUEST_SELECT_FILE) {
//                if (uploadMessage == null)
//                    return;
//                uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
//                uploadMessage = null;
//            }
//        } else if (requestCode == FILECHOOSER_RESULTCODE) {
//            if (null == mUploadMessage)
//                return;
//            // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
//            // Use RESULT_OK only if you're implementing WebView inside an Activity
//            Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
//            mUploadMessage.onReceiveValue(result);
//            mUploadMessage = null;
//        } else
//            Toast.makeText(getBaseContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
//    }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_SELECT_FILE) {

        if (null == mUploadMessage && null == mUploadCallbackAboveL) {
            return;
        }
        Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
        if (mUploadCallbackAboveL != null) {
            onActivityResultAboveL(requestCode, resultCode, data);
        } else if (mUploadMessage != null) {
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
    }else if (requestCode == VIDEO_REQUEST) {
        if (null == mUploadMessage && null == mUploadCallbackAboveL) return;

        Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
        if (mUploadCallbackAboveL != null) {
            if (resultCode == RESULT_OK) {
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
                mUploadCallbackAboveL = null;
            } else {
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{});
                mUploadCallbackAboveL = null;
            }

        } else if (mUploadMessage != null) {
            if (resultCode == RESULT_OK) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            } else {
                mUploadMessage.onReceiveValue(Uri.EMPTY);
                mUploadMessage = null;
            }

        }
    }
}

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != REQUEST_SELECT_FILE || mUploadCallbackAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
                results = new Uri[]{imageUri};
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
    }
    //html上传图片、视频
    private ValueCallback<Uri[]> mUploadMessageA5;
    /**
     * 注意申请读取相机和读取内存的权限
     */
    private void startGetPhoto() {
        FastPermission.with(WebActivity.this)
                .permissions(Permission.CAMERA,Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onPermissionSuccess() {
                        showPhotoChooser();
                    }
                    @Override
                    public void onPermissionFailure(String hint) {
                        N.showShort(WebActivity.this,hint);
                    }
                });

    }
    private void startGetVideo() {
        FastPermission.with(WebActivity.this)
                .permissions(Permission.CAMERA,Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onPermissionSuccess() {
                        recordVideo();
                    }
                    @Override
                    public void onPermissionFailure(String hint) {
                        N.showShort(WebActivity.this,hint);
                    }
                });

    }
    class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        @TargetApi(21)
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mUploadCallbackAboveL = filePathCallback;
            acceptType = fileChooserParams.getAcceptTypes()[0];
            if(acceptType.contains("video")){
                isVideo=true;
            }else{
                isVideo=false;
            }
            if (isVideo){
                startGetVideo();
            }else {
                startGetPhoto();
            }
            return true;
        }

    }
    public void openFileChooser(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        if (isVideo){
            startGetVideo();
        }else {
            startGetPhoto();
        }
    }

    // For Android 3.0+
    public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
        mUploadMessage = uploadMsg;
        acceptType = acceptType;
        if (isVideo){
            startGetVideo();
        }else {
            startGetPhoto();
        }
    }

    //For Android 4.1
    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
        mUploadMessage = uploadMsg;
        acceptType = acceptType;
        if (isVideo){
            startGetVideo();
        }else {
            startGetPhoto();
        }
    }
    /**
     * 打开选择文件/相机
     */
    private void showPhotoChooser() {

        Intent intentPhoto = new Intent(Intent.ACTION_PICK);
        intentPhoto.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//        Intent intentPhoto = new Intent(Intent.ACTION_GET_CONTENT);
//        intentPhoto.addCategory(Intent.CATEGORY_OPENABLE);
//        intentPhoto.setType("*/*");
        File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
        if(!fileUri.exists()){
            fileUri.getParentFile().mkdirs();
        }
         imageUri = Uri.fromFile(fileUri);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            imgUri = FileProvider.getUriForFile(WebActivity.this, "com.wlbx.agent.fileprovider", compressFile);

            imageUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
        }
        //调用系统相机
        Intent intentCamera = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intentCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        //将拍照结果保存至photo_file的Uri中，不保留在相册中
        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        Intent chooser = new Intent(Intent.ACTION_CHOOSER);
        chooser.putExtra(Intent.EXTRA_TITLE, "选择方式");
        chooser.putExtra(Intent.EXTRA_INTENT, intentPhoto);
        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{intentCamera});
        startActivityForResult(chooser, REQUEST_SELECT_FILE);
    }
    /**
     * 录像
     */
    private void recordVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        //限制时长
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 3);
        //开启摄像机
        startActivityForResult(intent, VIDEO_REQUEST);
    }
//    private void openCameraOrAlbum(final String acceptTypes) {
//        FastPermission.with(this)
//        .permissions(Permission.CAMERA,Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE)
//        .request(new OnPermissionCallback() {
//            @Override
//            public void onPermissionSuccess() {
//                if("image/*".equals(acceptTypes)){
//                ImagePicker.withMulti(new WeChatPresenter())
//                        .setMaxCount(1)
//                        .setColumnCount(4)
//                        .mimeTypes(MimeType.JPEG, MimeType.PNG)
//                        .setPreview(true)
//                        .showCamera(true)
//                        .pick(WebActivity.this, new OnImagePickCompleteListener2() {
//                            @Override
//                            public void onPickFailed(PickerError error) {
////                                N.showShort(WebActivity.this, error.getMessage());
//                                uploadNullValue();
//                            }
//
//                            @Override
//                            public void onImagePickComplete(ArrayList<ImageItem> items) {
//                                uploadCompressImage(items.get(0));
//                            }
//                        });
//            }else if("video/*".equals(acceptTypes)){
//
//                    ImagePicker.withMulti(new WeChatPresenter())
//                                    .setMaxCount(1)
//                                    .setColumnCount(4)
//                                    .mimeTypes(MimeType.ofVideo())
//                                    .setMaxVideoDuration(3000L)
//                                    .setMinVideoDuration(2000L)
//                                    .setPreview(true)
//                                    .showCamera(true)
//                                    .pick(WebActivity.this, new OnImagePickCompleteListener2() {
//                                        @Override
//                                        public void onPickFailed(PickerError error) {
////                                            N.showShort(WebActivity.this, error.getMessage());
//                                            uploadNullValue();
//                                        }
//
//                                        @Override
//                                        public void onImagePickComplete(ArrayList<ImageItem> items) {
//                                            uploadCompressVideo(items.get(0));
//                                        }
//                                    });
//                        }else {
//                            Toast.makeText(WebActivity.this, "支持传入以下MIME类型：image/* or video/*", Toast.LENGTH_SHORT).show();
//                        }
//
//     }
//            @Override
//            public void onPermissionFailure(String hint) {
//                N.showShort(WebActivity.this, hint);
//                uploadNullValue();
//            }
//        });
//    }

    //上传空值
//    private void uploadNullValue() {
//        if (mUploadMessageA5 != null) {
//            mUploadMessageA5.onReceiveValue(null);
//            mUploadMessageA5 = null;
//        }
//    }
    //上传压缩视频
//    private void uploadCompressVideo(final ImageItem imageItem) {
//        if (imageItem == null) {
//            uploadNullValue();
//            return;
//        }
//        File rawFile = new File(imageItem.getPath());
//        final File compressFile = new File(getCacheDir().getAbsolutePath(),rawFile.getName());
//        if (compressFile.exists()) {
//            compressFile.delete();
//        }
//        try {
//            compressFile.createNewFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
////        File rawFile = new File(imageItem.getPath());
//        Uri videoUri = Uri.fromFile(compressFile);
//        if (mUploadMessageA5 != null) {
//            mUploadMessageA5.onReceiveValue(new Uri[]{videoUri});
//            mUploadMessageA5 = null;
//        }
////        if (imageItem == null) {
////            uploadNullValue();
////            return;
////        }
////        File rawFile = new File(imageItem.getPath());
////        final File compressFile = new File(getCacheDir().getAbsolutePath(),rawFile.getName());
////        if (compressFile.exists()) {
////            compressFile.delete();
////        }
////        try {
////            compressFile.createNewFile();
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
////        debugI("视频压缩前：", rawFile.getAbsolutePath() + " " + Formatter.formatFileSize(this, FileUtils.getFileSize(rawFile.getAbsolutePath())));
////        RxFFmpegInvoke.getInstance()
////                .runCommandRxJava(getFFmpegVideoCompressCommand(rawFile.getAbsolutePath(), compressFile.getAbsolutePath()))
////                .subscribe(new RxFFmpegSubscriber() {
////                    @Override
////                    public void onFinish() {
////                        debugI("视频压缩后：", compressFile.getAbsolutePath() + " " + Formatter.formatFileSize(WebActivity.this, FileUtils.getFileSize(compressFile.getAbsolutePath())));
////                        Uri videoUri;
////                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
////                            videoUri = FileProvider.getUriForFile(WebActivity.this, "com.wlbx.agent.fileprovider", compressFile);
////                        else
////                            videoUri = Uri.fromFile(compressFile);
////                        debugI("视频压缩后uri：", videoUri.toString());
////                        if (mUploadMessageA5 != null) {
////                            mUploadMessageA5.onReceiveValue(new Uri[]{videoUri});
////                            mUploadMessageA5 = null;
////                        }
////                    }
////
////                    @Override
////                    public void onProgress(int progress, long progressTime) {
////                        debugI("视频压缩执行进度：" + progress);
////                    }
////
////                    @Override
////                    public void onCancel() {
////                        debugI("视频压缩取消");
////                        uploadNullValue();
////                    }
////
////                    @Override
////                    public void onError(String message) {
////                        debugI("视频压缩失败：" + message);
////                        uploadNullValue();
////                    }
////                });
//    }

    //构建命令,使用RxFFmpegCommandList可以有效避免路径带有空格等问题。
    //视频压缩命令:ffmpeg -y -i /storage/emulated/0/1/input.mp4 -b 2097k -r 30 -vcodec libx264 -preset superfast /storage/emulated/0/1/result.mp4
//    public static String[] getFFmpegVideoCompressCommand(String rawVideoFilePath,String compressVideoFilePath) {
//        RxFFmpegCommandList cmdlist = new RxFFmpegCommandList();
//        cmdlist.append("-i").append(rawVideoFilePath);
//        cmdlist.append("-b").append("2097k");
//        cmdlist.append("-r").append("30");
//        cmdlist.append("-vcodec").append("libx264");
//        cmdlist.append("-preset").append("superfast").append(compressVideoFilePath);
//        return cmdlist.build();
//    }
    class MyWebViewClient extends BridgeWebViewClient {

        public MyWebViewClient() {
            super(wvContent);
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            debugI("shouldOverrideUrlLoading:", url);
            if(url.startsWith("tel:")){
                Intent intent=new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            }
            else if(url.startsWith("weixin://wap/pay?")||
                    url.contains("qr.alipay.com") ||
                    url.startsWith("alipays:")||
                    url.startsWith("alipay") ||
                    url.startsWith("wvjbscheme://") ||
                    url.startsWith("yy://")){
                try{
                    startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(url)));
                }catch (Exception e){
                    //e.printStackTrace();
//                    N.showShort(WebActivity.this,e.toString());
                }
                return true;
            }
            if(url.startsWith("https://wx.tenpay.com") || url.startsWith("https://m.inswin.cn")){
                Map<String,String> extraHeader=new HashMap<>();
                String currUrl = getCurrUrl();
                int index = getCharAtStringIndex(currUrl, 3, "/");
                String root = currUrl.substring(0,index);//例如root：https://yldap.pa18.com
                extraHeader.put("Referer",root);
                wvContent.loadUrl(url,extraHeader);
                debugI("申请H5时提交的授权域名:" + root);
                return true;
            }
            else if(url.toLowerCase().contains("platformapi") && url.toLowerCase().contains("startapp")){
                try {
                    Intent intent = Intent.parseUri(url,Intent.URI_INTENT_SCHEME);
                    intent.addCategory(Intent.CATEGORY_BROWSABLE);
                    intent.setComponent(null);
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
            else if(!TextUtils.isEmpty(url) && !url.endsWith(".pdf")){ //pdf文件不能直接在webview中显示，要先下载在调用外部app显示
                if (openType == OPEN_CURRENT) {
                    if(urls.size()>0) {
                        urls.removeFirst();
                    }
                    urls.addFirst(url);
                    refresh(urls.getFirst());
                }else{
                    urls.addFirst(url);
                    showInNewPage(urls.getFirst());
                }
            } else if(url.endsWith(".pdf")){
                refresh(url);
            }
            maskFlag();
            return true;
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            view.getSettings().setBlockNetworkImage(false);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //super.onReceivedSslError(view, handler, error);
            handler.proceed();
            if(error.getPrimaryError() == SslError.SSL_INVALID ){// 校验过程遇到了bug
                handler.proceed();
            }else{
                handler.cancel();
            }
        }
    }

    public void registerHandler(BridgeWebView wvContent){
        wvContent.registerHandler("getAgentData", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                String ret = getAgentData(data);
                Logger.i("getAgentData---"+ ret);
                function.onCallBack(ret);
            }
        });

        wvContent.registerHandler("showTitle", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Logger.i(TAG, data);
                String ret = showTitle(data);
                function.onCallBack(ret);
            }
        });

        wvContent.registerHandler("weixinShare", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Logger.i(TAG, data);
                String ret = weixinShare(data);
                function.onCallBack(ret);
            }
        });

        wvContent.registerHandler("weixinShareImage", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Logger.i(TAG, data);
                String ret = weixinShareImage(data);
                function.onCallBack(ret);
            }
        });

        wvContent.registerHandler("appointViewController", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Logger.i(TAG, data);
                String ret = appointViewController(data);
                function.onCallBack(ret);
            }
        });

        wvContent.registerHandler("backLastPage", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Logger.i(TAG, data);
                String ret = backLastPage(data);
                function.onCallBack(ret);
            }
        });

        wvContent.registerHandler("browserEnvironment", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                String ret = browserEnvironment(data);
                function.onCallBack(ret);
            }
        });

        wvContent.registerHandler("takeCamera",new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                String ret = openCamera(data);
                function.onCallBack(ret);
            }
        });

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(!wvContent.canGoBack()){
                this.finish();
            }else{
                wvContent.goBack();
            }
            return  true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //================================工银安盛 start===================================================
    //添加合作机构“工银安盛”的保险产品网页所需的对应的原生接口
    private void add_ICBC_AXA_javascriptInterface(final BridgeWebView bridgeWebView, final Gson gson){
        //拍照和相册
        bridgeWebView.registerHandler("camera", new BridgeHandler() {
            @Override
            public void handler(final String data, CallBackFunction function) {
                toCamera(bridgeWebView,gson,data);
            }
        });
        //分享
        bridgeWebView.registerHandler("shareWeChat", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                toShare(function,gson,data);
            }
        });
        //获取用户地理位置信息
        bridgeWebView.registerHandler("geographic", new BridgeHandler() {
            @Override
            public void handler(String data, final CallBackFunction function) {
                toLocation(function, gson);
            }
        });
    }

    private void toCamera(final BridgeWebView bridgeWebView,final Gson gson,String data) {
        if(TextUtils.isEmpty(data)){
            N.showShort(WebActivity.this,"js send to app data is null");
        }else {
            final ImageOptionBeen been = gson.fromJson(data, ImageOptionBeen.class);

            if(been.isOCR || been.isCamera){
                FastPermission.with(WebActivity.this)
                        .permissions(Permission.CAMERA,Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onPermissionSuccess() {
                                ImagePicker.takePhoto(WebActivity.this, null, true, new OnImagePickCompleteListener() {
                                    @Override
                                    public void onImagePickComplete(ArrayList<ImageItem> items) {
                                        handleAndUploadImage(bridgeWebView,gson,items);
                                    }
                                });
                            }
                            @Override
                            public void onPermissionFailure(String hint) {
                                N.showShort(WebActivity.this,hint);
                            }
                        });
            }else if (been.isMultiple){
                FastPermission.with(this)
                        .permissions(Permission.CAMERA,Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onPermissionSuccess() {
                                ImagePicker.withMulti(new WeChatPresenter())
                                        .setMaxCount(been.count)
                                        .setColumnCount(4)
                                        .mimeTypes(MimeType.JPEG, MimeType.PNG)
                                        .setPreview(true)
                                        .showCamera(false)
                                        .pick(WebActivity.this, new OnImagePickCompleteListener2() {

                                            @Override
                                            public void onPickFailed(PickerError error) {
                                                N.showShort(WebActivity.this, error.toString());
                                            }

                                            @Override
                                            public void onImagePickComplete(ArrayList<ImageItem> items) {
                                                handleAndUploadImage(bridgeWebView, gson, items);
                                            }
                                        });
                            }

                            @Override
                            public void onPermissionFailure(String hint) {
                                N.showShort(WebActivity.this, hint);
                            }
                        });
            }else {
                FastPermission.with(this)
                        .permissions(Permission.CAMERA,Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onPermissionSuccess() {
                                ImagePicker.withMulti(new WeChatPresenter())
                                        .setMaxCount(1)
                                        .setColumnCount(4)
                                        .mimeTypes(MimeType.JPEG,MimeType.PNG)
                                        .setPreview(true)
                                        .showCamera(true)
                                        .pick(WebActivity.this, new OnImagePickCompleteListener2() {
                                            @Override
                                            public void onPickFailed(PickerError error) {
                                                N.showShort(WebActivity.this,error.toString());
                                            }

                                            @Override
                                            public void onImagePickComplete(ArrayList<ImageItem> items) {
                                                handleAndUploadImage(bridgeWebView,gson,items);
                                            }
                                        });
                            }

                            @Override
                            public void onPermissionFailure(String hint) {
                                N.showShort(WebActivity.this, hint);
                            }
                        });
            }
        }
    }

    //上传压缩图片
    private void uploadSingleCompressImage(final ImageItem imageItem) {
        if (imageItem == null) {
            return;
        }
        File file = new File(FileUtil.getRealPathFromUri(this,imageItem.getUri()));
        Luban.with(this)
                .load(file)
                //.setTargetDir(getCacheDir().getAbsolutePath())
                .ignoreBy(100)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        debugI("图片压缩前：", imageItem.getPath() + " " + Formatter.formatFileSize(WebActivity.this, FileUtils.getFileSize(file.getAbsolutePath())));
                    }

                    @Override
                    public void onSuccess(File compressFile) {
                        debugI("图片压缩后：", compressFile.getAbsolutePath() + " " + Formatter.formatFileSize(WebActivity.this, FileUtils.getFileSize(compressFile.getAbsolutePath())));
                        Uri imgUri;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            imgUri = FileProvider.getUriForFile(WebActivity.this, "com.wlbx.agent.fileprovider", compressFile);
                        else
                            imgUri = Uri.fromFile(compressFile);
                        debugI("图片压缩后uri：", imgUri.toString());
                        dealSingleFile(compressFile);
                    }

                    @Override
                    public void onError(Throwable e) {
                        N.showShort(WebActivity.this, "图片压缩失败：" + e.toString());
                    }
                })
                .launch();
    }

    //上传压缩图片
//    private void uploadCompressImage(final ImageItem imageItem) {
//        if (imageItem == null) {
//            uploadNullValue();
//            return;
//        }
//        Luban.with(this)
//                .load(FileUtil.getRealPathFromUri(this,imageItem.getUri()))
//                .setTargetDir(getCacheDir().getAbsolutePath())
//                .ignoreBy(100)
//                .setCompressListener(new OnCompressListener() {
//                    @Override
//                    public void onStart() {
//                        debugI("图片压缩前：", imageItem.getPath() + " " + Formatter.formatFileSize(WebActivity.this, FileUtils.getFileSize(imageItem.getPath())));
//                    }
//
//                    @Override
//                    public void onSuccess(File compressFile) {
//                        debugI("图片压缩后：", compressFile.getAbsolutePath() + " " + Formatter.formatFileSize(WebActivity.this, FileUtils.getFileSize(compressFile.getAbsolutePath())));
//                        Uri imgUri;
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
//                            imgUri = FileProvider.getUriForFile(WebActivity.this, "com.wlbx.agent.fileprovider", compressFile);
//                        else
//                            imgUri = Uri.fromFile(compressFile);
//                        debugI("图片压缩后uri：", imgUri.toString());
//                        if (mUploadMessageA5 != null) {
//                            mUploadMessageA5.onReceiveValue(new Uri[]{imgUri});
//                            mUploadMessageA5 = null;
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        N.showShort(WebActivity.this, "图片压缩失败：" + e.toString());
//                        uploadNullValue();
//                    }
//                })
//                .launch();
//    }

    private void handleAndUploadImage(final BridgeWebView bridgeWebView, final Gson gson, final ArrayList<ImageItem> imageItems) {
        for (int i = 0; i < imageItems.size(); i++) {
            ImageItem imageItem = imageItems.get(i);
            try {
                debugI("图片压缩前：",imageItem.getPath()+" "+ FileUtils.getFileSize(imageItem.getPath())/1024+"KB ");
                File  compressFile = Luban.with(this).setTargetDir(getCacheDir().getAbsolutePath()).ignoreBy(100).get(FileUtil.getRealPathFromUri(this,imageItem.getUri()));
                debugI("图片压缩后：",compressFile.getAbsolutePath()+" "+ FileUtils.getFileSize(compressFile.getAbsolutePath())/1024+"KB ");
                String imageToBase64Str = "data:image/png;base64,"+ imageToBase64(compressFile.getAbsolutePath());
                ImageUploadBeen been = new ImageUploadBeen();
                been.image = imageToBase64Str;
                been.count = imageItems.size();
                String json = gson.toJson(been);
                //bridgeWebView.callHandler("acceptMultiImages", json, null);
                bridgeWebView.callHandler("acceptMultiImages", json, new CallBackFunction() {
                    @Override
                    public void onCallBack(String data) {
                        debugI("图片上传后返回数据："+data);
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void dealFile(File compressFile, ArrayList<ImageItem> imageItems){
        debugI("图片压缩后：",compressFile.getAbsolutePath()+" "+ FileUtils.getFileSize(compressFile.getAbsolutePath())/1024+"KB ");
        String imageToBase64Str = "data:image/png;base64,"+ imageToBase64(compressFile.getAbsolutePath());
        ImageUploadBeen been = new ImageUploadBeen();
        been.image = imageToBase64Str;
        been.count = imageItems.size();
        String json = gson.toJson(been);
        Logger.i("上传H5文件长度："+been.image.length());
        wvContent.callHandler("cameraBack", ""+compressFile.length(), new CallBackFunction() {
            @Override
            public void onCallBack(String data) {
                debugI("图片上传后返回数据："+data);
            }
        });
    }

    public void dealSingleFile(File compressFile){
        debugI("图片压缩后：",compressFile.getAbsolutePath()+" "+ FileUtils.getFileSize(compressFile.getAbsolutePath())/1024+"KB ");
        String imageToBase64Str = imageToBase64(compressFile.getAbsolutePath());
        Logger.i("上传H5文件长度："+imageToBase64Str.length());
        JSONObject json = new JSONObject();
        json.put("base64image",imageToBase64Str);
        wvContent.callHandler("cameraBack", json.toJSONString(), new CallBackFunction() {
            @Override
            public void onCallBack(String data) {
                debugI("图片上传后返回数据："+data);
            }
        });
    }

    /**
     * 将图片转换成Base64编码的字符串
     */
    public static String imageToBase64(String path){
        if(TextUtils.isEmpty(path)){
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try{
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data,Base64.NO_CLOSE);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null !=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }

    private class ImageOptionBeen {
        /**
         * isOCR : false
         * isCamera : true
         * isMultiple : true
         * count : 1
         */
        public boolean isOCR;       //是否只用于OCR，优先判断此参数，OCR只能打开摄像头
        public boolean isCamera;    //是否只打开摄像头，默认打开摄像头和相册
        public boolean isMultiple;  //是否多选，默认多选
        public int count;           //相册多选最大数，只有当isMultiple为true时才有效，默认为1，最大为9张
    }

    private class ImageUploadBeen{
        public String image;
        public int count;
    }

    public void toShare(final CallBackFunction function,final Gson gson,String data){
        if(TextUtils.isEmpty(data)){
            N.showShort(WebActivity.this,"js send to app data is null");
        }else {
            final ShareOptionBeen been = gson.fromJson(data, ShareOptionBeen.class);

            if(TextUtils.isEmpty(been.imgUrl)){
                N.showShort(WebActivity.this,"分享图标链接为空，无法分享");
                return;
            }
            Glide.with(this).asBitmap().load(been.imgUrl)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull final Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
                        switch (been.channel) {
                            case "0":
                                ShareDialog shareDialog = new ShareDialog(WebActivity.this);
                                shareDialog.setMonShare(new ShareDialog.onShare(){

                                    @Override
                                    public void onShareToWeixin(){
                                        ShareUtil.shareToWeiXin(WebActivity.this,been.title,been.desc,been.link,bitmap);
                                        sendShareSuccessCallback(function, gson);
                                    }

                                    @Override
                                    public void onShareToFriends(){
                                        ShareUtil.shareToFriends(WebActivity.this,been.title,been.desc,been.link,bitmap);
                                        sendShareSuccessCallback(function, gson);
                                    }
                                });
                                shareDialog.show();
                                break;
                            case "1":
                                ShareUtil.shareToWeiXin(WebActivity.this,been.title,been.desc,been.link,bitmap);
                                sendShareSuccessCallback(function, gson);
                                break;
                            case "2":
                                ShareUtil.shareToFriends(WebActivity.this,been.title,been.desc,been.link,bitmap);
                                sendShareSuccessCallback(function, gson);
                                break;
                        }
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        N.showShort(WebActivity.this, "分享图标下载异常，无法分享");
                    }
                });
        }
    }

    private void sendShareSuccessCallback(CallBackFunction function, Gson gson) {
        ShareSuccessBeen obj = new ShareSuccessBeen();
        obj.code = "1";
        obj.message = null;
        obj.data = null;
        function.onCallBack(gson.toJson(obj));
    }

    private class ShareSuccessBeen{
        public String code;     //string  '1'-成功  '0'-失败
        public String data;     //JSONstring  成功具体数据
        public String message;  //string  失败信息
    }

    private class ShareOptionBeen{
        /**
         * channel : 1
         * title : 工银安盛人寿
         * desc : 工银安盛人寿
         * link : https://mcpuat.icbc-axa.com/mcp-as/react/questionnaire?agentCode=T0034548&policyNumber=ZJ192713639&agentChannel=010&clientType=002&share=yes
         * imgUrl : https://mcpuat.icbc-axa.com/mcp-as/ebt/components/base/img/app_icon.png
         */

        public String channel;  //分享渠道 '0'-全部(弹窗) '1'-好友 '2'-朋友圈
        public String title;    //分享标题
        public String desc;     //分享描述
        public String link;     //分享链接，必传
        public String imgUrl;   //分享图标链接
    }

    private void toLocation(final CallBackFunction function, final Gson gson) {
        FastPermission.with(this)
                .permissions(Permission.ACCESS_FINE_LOCATION,Permission.ACCESS_COARSE_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onPermissionSuccess() {
                        LocationUtil.registerNetworkProviderLocation(WebActivity.this, 300, 0, new LocationUtil.OnLocationChangeListener() {
                            @Override
                            public void onLastKnownLocation(Location location) {
                            }

                            @Override
                            public void startLocationUpdate() {
                                showWaitingDialog();
                            }

                            @Override
                            public void onLocationChanged(Location location) {
                                //位置信息变化时触发
                                debugI("定位方式：" + location.getProvider());
                                debugI("经度：" + location.getLongitude());
                                debugI("纬度：" + location.getLatitude());
                                debugI("地理位置：" + LocationUtil.getAddress(WebActivity.this, location.getLatitude(), location.getLongitude()));
                                debugI("国家：" + LocationUtil.getCountryName(WebActivity.this, location.getLatitude(), location.getLongitude()));
                                debugI("省：" + LocationUtil.getProvince(WebActivity.this, location.getLatitude(), location.getLongitude()));
                                debugI("市：" + LocationUtil.getCity(WebActivity.this, location.getLatitude(), location.getLongitude()));
                                debugI("区县：" + LocationUtil.getDistrict(WebActivity.this, location.getLatitude(), location.getLongitude()));
                                debugI("乡镇：" + null);
                                debugI("街道：" + null);
                                debugI("路：" + null);
                                debugI("建筑 楼宇 小区：" +null);
                                LocationUtil.unregister();
                                LocationBeen been = new LocationBeen();
                                been.longitude = String.valueOf(location.getLongitude());
                                been.latitude = String.valueOf(location.getLatitude());
                                been.province = LocationUtil.getProvince(WebActivity.this, location.getLatitude(), location.getLongitude());
                                been.city = LocationUtil.getCity(WebActivity.this, location.getLatitude(), location.getLongitude());
                                been.district = LocationUtil.getDistrict(WebActivity.this, location.getLatitude(), location.getLongitude());
                                been.township = null;
                                been.street = null;
                                been.road = null;
                                been.building = null;
                                String json = gson.toJson(been);
                                GeographicBeen obj = new GeographicBeen();
                                obj.code = "1";
                                obj.message = null;
                                obj.data = json;
                                function.onCallBack(gson.toJson(obj));
                            }

                            @Override
                            public void endLocationUpdate() {
                                dismissWaitingDialog();
                            }
                        });
                    }

                    @Override
                    public void onPermissionFailure(String hint) {
                        N.showShort(WebActivity.this,hint);
                    }
                });
    }

    private class GeographicBeen{
        public String code;     //string  '1'-成功  '0'-失败
        public String data;     //JSONstring  成功具体数据
        public String message;  //string  失败信息
    }

    private class LocationBeen {
        public String longitude;//经度
        public String latitude; //纬度
        public String province; //省
        public String city;     //市
        public String district; //区县
        public String township; //乡镇
        public String street;   //街道
        public String road;     //路
        public String building; //建筑 楼宇 小区
    }

    protected void refresh(String url){
        wvContent.loadUrl(url);
    }

    protected void showInNewPage(String url){
        if (wvContent!=null){
            wvContent.loadUrl(url);
        }
        if (!TextUtils.isEmpty(url) && url.contains("planPageUrl=") && url.contains("customerPlanInfoId="))
            mPlanShareUrl =url;
        else
            mPlanShareUrl=null;
    }

    protected String getCurrUrl(){
        if(urls.isEmpty()){
            finish();
            return "";
        }
        return urls.getFirst();
    }

    private boolean checkIfCloseNow(){
        Uri uri=Uri.parse(getCurrUrl());
        if(uri.getBooleanQueryParameter("closeFlag",false)) {
            finish();
            return true;
        }
        else if("paySuccess".equals(uri.getQueryParameter("target"))){
            finish();
            return true;
        }
        return false;
    }

    /**
     * @param string 字符串
     * @param i      第i次出现
     * @param str    子字符串
     * @return       子字符串在字符串中第i次出现的索引
     */
    private static int getCharAtStringIndex(String string, int i, String str) {
        Matcher m = Pattern.compile(str).matcher(string);
        int mIdx = 0;
        while (m.find()) {
            mIdx++;
            if (mIdx == i) {
                break;
            }
        }
        return m.start();
    }

    /**
     * 遮罩flag
     */
    private void maskFlag(){
//        Uri uri=Uri.parse(getCurrUrl());
//        String maskColor=uri.getQueryParameter("maskColor");
//        if(!TextUtils.isEmpty(maskColor)) {
//            try {
//                mMask.setBackgroundColor(Color.parseColor(maskColor));
//            } catch (IllegalArgumentException e) {
//                //浏览器中的一些操作以高包容性来处理
//            }
//        }
    }

    //================================工银安盛 end===================================================

    private void showPopupValidCodeWindow() {
        if (mPopupShareWindow != null && mPopupShareWindow.isShowing()) {
            mPopupShareWindow.dismiss();
        } else {
            View view = mInflater.inflate(R.layout.pop_share_select, null);
            TextView tvWx = view.findViewById(R.id.tv_pop_wx);
            TextView tvFriend = view.findViewById(R.id.tv_pop_friend);
            tvWx.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(product != null) {
                        JSONObject json = new JSONObject();
                        json.put("shareType", "0");
                        json.put("titleName", product.getProductName());
                        if(product.getProductAbbrDescription() == null){
                            json.put("describe",product.getProductName());
                        }else {
                            json.put("describe", product.getProductAbbrDescription());
                        }
                        json.put("shareUrl", product.getProductUrl());
                        json.put("imageUrl", product.getLogoUrl());
                        weixinShare(json.toJSONString());
                        Logger.i(json.toJSONString());
                        mPopupShareWindow.dismiss();
                    }else{
                        Toast.makeText(mContext,"没有找到产品信息",Toast.LENGTH_SHORT).show();
                        mPopupShareWindow.dismiss();
                    }
                }
            });
            tvFriend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(product != null) {
                        JSONObject json = new JSONObject();
                        json.put("shareType","1");
                        json.put("titleName",product.getProductName());
                        if(product.getProductAbbrDescription() == null){
                            json.put("describe",product.getProductName());
                        }else {
                            json.put("describe", product.getProductAbbrDescription());
                        }
                        json.put("shareUrl",product.getProductUrl());
                        json.put("imageUrl",product.getLogoUrl());

                        weixinShare(json.toJSONString());
                        Logger.i(json.toJSONString());
                        mPopupShareWindow.dismiss();
                    }else{
                        Toast.makeText(mContext,"没有找到产品信息",Toast.LENGTH_SHORT).show();
                        mPopupShareWindow.dismiss();
                    }
                }
            });
            mPopupShareWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            mPopupShareWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            mPopupShareWindow.setFocusable(true);
            mPopupShareWindow.getContentView().setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    mPopupShareWindow.setFocusable(false);
                    mPopupShareWindow.dismiss();
                    return true;
                }
            });
            mPopupShareWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0);
        }
    }
    //压缩图片到32K
    private Bitmap getBitmap(Bitmap bitmap){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        while ( baos.toByteArray().length / 1024>32) {
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
            options -= 10;
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        return BitmapFactory.decodeStream(isBm, null, null);
    }

    //Bitmap转化为字节
    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        int i;
        int j;
        if (bmp.getHeight() > bmp.getWidth()) {
            i = bmp.getWidth();
            j = bmp.getWidth();
        } else {
            i = bmp.getHeight();
            j = bmp.getHeight();
        }
        Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
        Canvas localCanvas = new Canvas(localBitmap);
        while (true) {
            localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0,i, j), null);
            if (needRecycle)
                bmp.recycle();
            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    localByteArrayOutputStream);
            localBitmap.recycle();
            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
            try {
                localByteArrayOutputStream.close();
                return arrayOfByte;
            } catch (Exception e) {
                //F.out(e);
            }
            i = bmp.getHeight();
            j = bmp.getHeight();
        }
    }


}